#include "error.h"
#include "main.h"
#include <QApplication>
#include <QtDebug>
#include <QFile>
#include <QTextStream>
#include <QtGlobal>
#include <stdio.h>
#include "updatedialog.h"
#include "singleapplication.h"

#define DEBUG  1
#define SERVER_IP   "172.17.152.171"
#define SERVER_PORT 8080

QFile *outFile;

// Save log to file by invoked the callback function in application
void _loghandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString txt;
	txt = QString("%1").arg(msg);
    outFile = new QFile("./OtahelperClient.log");
    outFile->open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(outFile);
    ts << txt << endl;
}

static void initLog()
{
#if (DEBUG == 1)
    QDir currDir(".");
    if (currDir.exists("OtahelperClient.log"))
        currDir.remove("OtahelperClient.log");
    qInstallMessageHandler(_loghandler);
#endif
}

static void help()
{
	qDebug() << "" \
	" qt_simudisp [-p], process libota_sa.so popup_window request and simulate HU send user inputs events to host\n" \
	" -a, address of server socket or user_action pipe file path (default path: ${ESYNC_DATA_DIR}}/misc/ota_events/user_action)\n" \
	" -p, port of server socket";
}


int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
	initLog();
	OtaHelperCli u;

	UpdateDialog w(&u);
	a.installEventFilter(&w);

	QCommandLineParser parser;
	QCommandLineOption pathOp(QStringList() << "a" << "addr" << "Socket ipaddress or Pipe \"user_action\" path");
	parser.addOption(pathOp);
	QCommandLineOption portOp(QStringList() << "p" << "port" << "Socket port,(such as 5037)");
	parser.addOption(portOp);
	parser.process(a.arguments());
	QString addrPath = parser.value(pathOp);
	QString port = parser.value(portOp);
	if (addrPath.isEmpty() || port.isEmpty() || port.toInt()) {
		qDebug() << "ERROR: Not give the addrPath or port!" << endl;
		help();
		//exit(1);
	}
	//u.setSocketNetPath(addrPath.toLatin1(), port.toInt());
    u.setSocketNetPath(QByteArray(SERVER_IP), SERVER_PORT);
	u.start();

	w.showNormal();
	w.activateWindow();
	a.exec();
}
